package com.longfa.ojbackendjudgeservice.message;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * ClassName: InitRabbitMQ
 * Package: com.longfa.ojbackendjudgeservice
 * Description:用于创建测试程序用到的交换机和队列（只需要在程序启动前执行一次）
 *
 * @Author:
 * @Create: 2024/5/4 - 13:57
 * @Version: v1.0
 */
@Slf4j
public class InitRabbitMQ {

    /*@Value("${spring.rabbitmq.host}")
    private static String rabbitmqHost;
    @Value("${spring.rabbitmq.port}")
    private static int rabbitmqPort;
    @Value("${spring.rabbitmq.username}")
    private static String rabbitmqUsername;
    @Value("${spring.rabbitmq.password}")
    private static String rabbitmqPassword;*/
    /**
     * 为了方便用户使用，不需要在用户开启项目时，先执行main方法，这里将初始化RabbitMq交换机和队列的方法设置为静态方法，然后在springBoot
     * 启动类中调用一次
     */
    public static void doInit() {
        try {
            ConnectionFactory connectionFactory = new ConnectionFactory();
            connectionFactory.setHost("175.178.127.190");
            connectionFactory.setPort(5672);
            connectionFactory.setUsername("admin");
            connectionFactory.setPassword("admin");
            Connection connection = connectionFactory.newConnection();
            Channel channel = connection.createChannel();
            String exchange_name = "oj_exchange";
            channel.exchangeDeclare(exchange_name, BuiltinExchangeType.DIRECT);

            // 创建队列，随机分配一个队列名称
            String queue_name = "oj_queue";
            channel.queueDeclare(queue_name, true, false, false, null);
            channel.queueBind(queue_name, exchange_name, "question_judge");
            channel.close();
            connection.close();
            log.info("消息队列启动成功");
        } catch (IOException | TimeoutException e) {
            log.error("消息队列启动失败");
            throw new RuntimeException(e);
        }
    }

/*    public static void main(String[] args) {
        doInit();
    }*/
}
